import axios from 'axios'
import {ElMessage} from 'element-plus'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = 'https://note-server.hunger-valley.com'
axios.defaults.withCredentials = true

export default function request(url, type = 'GET', data = {}) {
  return new Promise((resolve, reject) => {
    let option = {
      url,
      method: type,
      validateStatus: function (status) {
        return (status >= 200 && status < 300) || status === 400
      }
    }
    if (type.toLowerCase() === 'get') {
      option.params = data
    } else {
      option.data = data
    }
    axios(option).then(res => {
      if (res.status === 200) {
        resolve(res.data)
      } else {
        ElMessage({
          type: 'error',
          message: res.data.msg,
        })
        reject(res.data)
      }
      // eslint-disable-next-line no-unused-vars
    }).catch(err => {
      ElMessage({
        type: 'error',
        message: '网络异常',
      })
      reject({msg: '网络异常'})
    })
  })
}
